<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <!-- 引入axios -->
  <script src="./js/axios.js"></script>
  <!-- vue 文件 -->
  <script src="js/vue.js"></script>
  <!-- 引入http-vue-loader -->
  <script src="./js/httpVueLoader.js"></script>
  <!-- element-ui 文件 -->
  <link rel="stylesheet" href="./css/element.css">
  <script src="./js/element.js"></script>
  <!-- css文件 -->
  <link rel="stylesheet" href="css/index.css">
  <style>
    .container {
      position: relative;
    }

    video {
      z-index: 1;
    }

    canvas {
      position: absolute;
      top: 0;
      left: 0;
      z-index: 2;
    }
  </style>
</head>

<body>
  <div id="app">
    <base-layout>
      <div class="container">
        <div class="video">
          <!-- <video ref="video" :src="'VideoIOServlet?fileName=' + videoData.url" id="vd" controls @play="handlePlay" @pause="handlePause"></video> -->
          <video ref="video" :src="'stream?video=' + videoData.url" id="vd" controls @play="handlePlay"
            @pause="handlePause" @timeupdate="timeupdateChange" :poster="videoData.img">error</video>
          <canvas ref="canvas" v-show="showCanvas"></canvas>
        </div>
        <div class="barrage-sending-area">
          <div class="barrage-sending-area-l">
            <p>共 <span class="barrage-num">{{ barrageList.length }}</span> 条弹幕</p>
            <span class="switch-box">
              <span class="switch-label">弹幕开关</span>
              <el-switch 
                v-model="isSelect" 
                active-color="#00aeec"
                inactive-color="#cccccc"
                @change="switchChange"
              ></el-switch>
            </span>
          </div>
          <div class="barrage-sending-area-r">
            <el-input 
              class="barrage-input" 
              v-model="barrageText" 
              placeholder="发个友善的弹幕见证下~" 
              @keyup.enter.native="addBarrage"
            ></el-input>
            <el-button class="button-box" @click="addBarrage">发送</el-button>
          </div>
        </div>
        <div class="introduce">
          <div class="video-title">{{ videoData.title }}</div>
          <div class="video-introduce">简介：{{ videoData.desc }}</div>
        </div>
        <div>
          <div class="remake-title">
            <span>评论</span>
            <span>{{ commentList.length }}</span>
          </div>
          <div class="remake-area">
            <el-input class="remake-input" v-model="commentText" placeholder="发个友善的评论~"></el-input>
            <el-button class="remake-btn" @click="addComment">发布评论</el-button>
          </div>
          <div class="remake-record">
            <div class="remake-record-one" v-for="item in commentList" :key="item.id">
              <div class="head-sculpture">
                <el-avatar :size="50" :src="item.avatar"></el-avatar>
              </div>
              <div class="remake-text">
                <div>{{item.user_id}}</div>
                <div>{{item.content}}</div>
                <div>{{item.createTime}}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </base-layout>
  </div>

  <script>
    Vue.use(httpVueLoader)
    //创建 vm 实例对象
    const vm = new Vue({
      components: {
        'base-layout': httpVueLoader('./components/BaseLayout.vue')
      },
      el: '#app',
      data: {
        showCanvas: true,
        isSelect: true,
        videoData: {
          title: '',
          desc: '',
          url: ''
        },
        barrageList: [],
        showBarrageList: [],
        barrageIndex: 0,
        paused: false,
        barrageText: '',
        commentText: '',
        commentList: []
      },
      created() {
        // 获取url的参数
        const params = new URLSearchParams(window.location.search);
        const id = params.get('id');

        // 发送请求
        axios.get(`http://localhost:8080/videoServlet.do?id=${id}`)
          .then(res => { 
            this.videoData = res.data
            this.videoData.img = this.videoData.img.indexOf('http') === 0 ? this.videoData.img : `http://localhost:8080/img/${this.videoData.img}`
        })
        this.loadBarrage(id);
        this.loadComment(id);
      },
      mounted() {
        // 生成匿名用户id
        this.userID = Math.floor(Math.random() * 1000000000);
        // 延迟2秒获取video标签
        setTimeout(() => {
          this.$nextTick(() => {
            this.video = this.$refs.video;
            // console.log(this.video);
            this.canvas = this.$refs.canvas;
            // console.log(this.canvas);
            this.context = this.canvas.getContext('2d');
            this.canvas.width = this.video.clientWidth;
            this.canvas.height = this.video.clientHeight * 0.5;
            this.context.font = '24px YaHei';
          })
        }, 2000);
      },
      updated() {
        if (this.barrageIndex !== 0) {
          this.drawBarrage();
        }
      },
      methods: {
        switchChange() {
          this.showCanvas = this.isSelect
        },
        // 加载弹幕数据
        async loadBarrage(id) {
          // 加载弹幕数据
          await axios.get(`http://localhost:8080/BarrageServlet.do?video_id=${id}`)
            .then(res => { this.barrageList = res.data })
        },
        // 加载评论数据
        async loadComment(id) {
          // 加载评论数据
          await axios.get(`http://localhost:8080/CommentServlet.do?video_id=${id}`)
            .then(res => { this.commentList = res.data })
        },
        // 播放视频
        handlePlay(e) {
          this.paused = false;
          this.drawBarrage();
        },
        // 暂停视频
        handlePause() {
          this.paused = true;
        },
        // 监听视频进度条更新
        timeupdateChange() {
          if(!this.showCanvas) return
          const time = parseInt(this.video.currentTime);
          // console.log(time);
          if (this.barrageIndex === time) {
            return
          }
          for (const item of this.barrageList) {
            if (time == item.position) {
              const barrage = {
                text: item.content,
                color: item.color,
                speed: 5,
                x: this.canvas.width,
                y: Math.random() * this.canvas.height,
              }
              // console.log(barrage);
              this.showBarrageList.push(barrage);
            }
          }
          // console.log(this.showBarrageList);
          this.barrageIndex = time
        },
        // 绘制弹幕
        drawBarrage() {
          // 清空画布
          this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
          // 绘制弹幕
          for (const barrage of this.showBarrageList) {
            // 设置弹幕颜色
            this.context.fillStyle = barrage.color;
            // 绘制弹幕
            this.context.fillText(barrage.text, barrage.x, barrage.y);
            // 弹幕移动
            barrage.x -= barrage.speed;
            // console.log(barrage.x);
            // 判断弹幕是否移出画布
            if (barrage.x < -this.context.measureText(barrage.text).width) {
              const index = this.showBarrageList.indexOf(barrage);// 获取弹幕索引
              this.showBarrageList.splice(index, 1);// 删除弹幕
            }
          }
          if (!this.paused && this.showCanvas) {
            // 递归绘制
            requestAnimationFrame(this.drawBarrage);
          }
        },
        // 发送弹幕
        addBarrage() {
          const video_id = this.videoData.id;
          const barrageText = this.barrageText.trim();
          if (barrageText === "") {
            return;
          }
          this.showBarrageList.push({
            text: barrageText,
            color: '#ffffff',
            speed: 5,
            x: this.canvas.width,
            y: Math.random() * this.canvas.height,
          })
          axios.post('http://localhost:8080/AddBarrageServlet.do', {
            video_id,
            content: barrageText,
            color: '#ffffff',
            position: parseInt(this.video.currentTime),
          }).then(res => {
            // console.log(res);
            this.loadBarrage(video_id);
          }).finally(() => {
            this.barrageText = '';
          })
        },
        // 评论
        addComment() {
          const commentText = this.commentText.trim();
          if (commentText === "") {
            return;
          }
          axios.post('http://localhost:8080/AddCommentServlet.do', {
            video_id: this.videoData.id,
            user_id: this.userID,
            content: commentText,
            avatar: 'https://iph.href.lu/50x50?text=匿&fg=666666&bg=cccccc'
          }).then(res => {
            // console.log(res);
          }).finally(() => {
            this.commentText = '';
            this.loadComment(this.videoData.id);
          })
        }
      },
    });
  </script>
</body>

</html>